package com.shop.cereshop.commons.tencent.moderation.util;

import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Base64;

/**
 * @description:  图片工具类
 * @author zdd
 * @date 2025/10/29 15:33
 * @version 1.0
 */
@Slf4j
public class ImageUtils {

    /**
     * 最大图像大小 5MB
     */
    private static final int MAX_IMAGE_SIZE = 5 * 1024 * 1024;

    /**
     * 连接超时 10秒
     */
    private static final int CONNECT_TIMEOUT = 10000;

    /**
     * 读取超时 30秒
     */
    private static final int READ_TIMEOUT = 30000;


    /**
     * 下载图片并转换为Base64
     * @param imageUrl 图片URL
     * @return Base64编码的图片数据
     */
    public static String downloadImageToBase64(String imageUrl) {
        HttpURLConnection connection = null;

        try {
            // 如果是HTTPS且需要跳过SSL验证
            if (imageUrl.startsWith("https://")) {
                disableSSLCertificateChecking();
            }

            URL url = new URL(imageUrl);
            connection = (HttpURLConnection) url.openConnection();

            // 设置通用参数
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            connection.setRequestProperty("Accept", "image/*");

            // 对于HTTPS，设置主机名验证器
            if (connection instanceof HttpsURLConnection) {
                ((HttpsURLConnection) connection).setHostnameVerifier((hostname, session) -> true);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                log.warn("图片下载失败，HTTP响应码: {}", responseCode);
                return null;
            }

            // 使用 try-with-resources 自动管理流资源
            try (InputStream inputStream = connection.getInputStream();
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                int totalBytes = 0;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;

                    if (totalBytes > MAX_IMAGE_SIZE) {
                        log.warn("图片数据流超过大小限制");
                        return null;
                    }
                }

                byte[] imageData = outputStream.toByteArray();

                if (imageData.length == 0) {
                    log.warn("下载的图片数据为空");
                    return null;
                }

                String base64Image = Base64.getEncoder().encodeToString(imageData);
                log.info("图片下载成功，大小: {} bytes", imageData.length);
                return base64Image;

            } catch (IOException e) {
                log.error("图片下载IO异常: {}", imageUrl, e);
                return null;
            }

        } catch (Exception e) {
            log.error("图片下载异常: {}", imageUrl, e);
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }


    /**
     * 禁用SSL证书验证
     */
    private static void disableSSLCertificateChecking() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };

            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);

        } catch (Exception e) {
            log.warn("禁用SSL证书验证失败", e);
        }
    }


    /**
     * 是否是 有效的url
     * @param url 图片url
     * return true/false
     */
    public static boolean isValidUrl(String url) {
        try {
            new URL(url);
            return true;
        } catch (MalformedURLException e) {
            return false;
        }
    }

    /**
     * 是否是 有效的图片格式
     * @param imageData 图片数据
     * return true/false
     */
    public static boolean isValidImageFormat(byte[] imageData) {
        // 简单的图片格式验证
        if (imageData.length < 8) return false;

        // JPEG: FF D8 FF
        if (imageData[0] == (byte) 0xFF && imageData[1] == (byte) 0xD8 && imageData[2] == (byte) 0xFF) {
            return true;
        }
        // PNG: 89 50 4E 47
        if (imageData[0] == (byte) 0x89 && imageData[1] == (byte) 0x50 &&
                imageData[2] == (byte) 0x4E && imageData[3] == (byte) 0x47) {
            return true;
        }
        // GIF: GIF8
        if (imageData[0] == 'G' && imageData[1] == 'I' && imageData[2] == 'F' && imageData[3] == '8') {
            return true;
        }

        log.warn("不支持的图片格式，文件头: {}", Arrays.copyOfRange(imageData, 0, Math.min(8, imageData.length)));
        return false;
    }


    private ImageUtils() {
        throw new UnsupportedOperationException("工具类不允许实例化");
    }

}
